package com.cms.kernel.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.cms.admin.service.AdminService;
import com.cms.kernel.entity.Admin;

/**
 * Copyright (C) 2013 2016 Well
 * 文件:AdminRealm.java
 * 创建:Well
 * 日期:2016年6月23日 下午3:20:52
 * 来自:
 * 版本:
 * 描述:后台管理员的权限校验
 */

public class AdminRealm extends AuthorizingRealm
{
	@Autowired
	private AdminService adminService;
	
	/**
	 * 用户授权和用户赋予角色，只是在缓存中没有用户的授权信息时调用
     * 负责在应用程序中决定用户的访问控制的方法
     * @param principalCollection
     * @return 
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
	{
		// TODO:授权功能暂未开发
		return null;
	}

	/**
	 * 登录校验
     * 当调用subject.login方法时，进入该方法
     * @param authenticationToken
     * @return
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException
	{
		AuthenticationInfo authenticationInfo=null;
		
		UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
		String username=token.getUsername(); // 登录名称
		Admin admin=adminService.getAdminByUsername(username); // 获取管理员对象
		if(null!=admin)
		{
			authenticationInfo=new SimpleAuthenticationInfo(admin, admin.getPassword(),super.getName());
			Subject subject=SecurityUtils.getSubject();
			Session session=subject.getSession(true);
			session.setAttribute("admin", admin);
		}
		
		return authenticationInfo;
	}

}
